<template>
  <div class="w-[80%] mx-auto p-8">
    <h1 class="text-2xl font-bold mb-8">{{ t('settings.title') }}</h1>
    
    <TabsRoot v-model="activeTab" class="w-full">
      <TabsList class="flex border-b border-gray-200 mb-6">
        <TabsTrigger value="general" class="px-4 py-2 -mb-[1px] text-sm font-medium text-gray-600 hover:text-gray-800 data-[state=active]:text-green-600 data-[state=active]:border-b-2 data-[state=active]:border-green-600">
          {{ t('settings.general') }}
        </TabsTrigger>
        <TabsTrigger value="models" class="px-4 py-2 -mb-[1px] text-sm font-medium text-gray-600 hover:text-gray-800 data-[state=active]:text-green-600 data-[state=active]:border-b-2 data-[state=active]:border-green-600">
          {{ t('settings.models') }}
        </TabsTrigger>
      </TabsList>

      <!-- 应用配置 -->
      <TabsContent value="general" class="space-y-6 max-w-[500px]">
        <!-- Language Setting -->
        <div class="setting-item flex items-center gap-8">
          <label class="text-sm font-medium text-gray-700 w-24">
            {{ t('settings.language') }}
          </label>
          <SelectRoot v-model="currentConfig.language" class="w-[160px]">
            <SelectTrigger class="inline-flex items-center justify-between rounded-md px-3 py-2 text-sm gap-1 bg-white border border-gray-300">
              <SelectValue :placeholder="t('settings.selectLanguage')" />
              <SelectIcon>
                <Icon icon="radix-icons:chevron-down" />
              </SelectIcon>
            </SelectTrigger>
            <SelectPortal>
              <SelectContent class="bg-white rounded-md shadow-lg border">
                <SelectViewport class="p-2">
                  <SelectGroup>
                    <SelectItem value="zh" class="relative flex items-center px-8 py-2 text-sm text-gray-700 rounded-md cursor-default hover:bg-gray-100">
                      <SelectItemText>{{ t('common.chinese') }}</SelectItemText>
                      <SelectItemIndicator class="absolute left-2 inline-flex items-center">
                        <Icon icon="radix-icons:check" />
                      </SelectItemIndicator>
                    </SelectItem>
                    <SelectItem value="en" class="relative flex items-center px-8 py-2 text-sm text-gray-700 rounded-md cursor-default hover:bg-gray-100">
                      <SelectItemText>{{ t('common.english') }}</SelectItemText>
                      <SelectItemIndicator class="absolute left-2 inline-flex items-center">
                        <Icon icon="radix-icons:check" />
                      </SelectItemIndicator>
                    </SelectItem>
                  </SelectGroup>
                </SelectViewport>
              </SelectContent>
            </SelectPortal>
          </SelectRoot>
        </div>

        <!-- Font Size Setting -->
        <div class="setting-item flex items-center gap-8">
          <label class="text-sm font-medium text-gray-700 w-24">
            {{ t('settings.fontSize') }}
          </label>
          <NumberFieldRoot v-model="currentConfig.fontSize" class="inline-flex w-[100px]">
            <NumberFieldDecrement class="px-2 border border-r-0 border-gray-300 rounded-l-md hover:bg-gray-100 focus:outline-none">
              <Icon icon="radix-icons:minus" />
            </NumberFieldDecrement>
            <NumberFieldInput 
              class="w-10 px-2 py-2 border border-gray-300 focus:outline-none focus:ring-1 focus:ring-green-500 text-center"
              :min="12"
              :max="20"
            />
            <NumberFieldIncrement class="px-2 border border-l-0 border-gray-300 rounded-r-md hover:bg-gray-100 focus:outline-none">
              <Icon icon="radix-icons:plus" />
            </NumberFieldIncrement>
          </NumberFieldRoot>
        </div>

        <!-- 主题色配置 -->
        <div class="setting-item flex items-center gap-8">
          <label class="text-sm font-medium text-gray-700 w-24">
            {{ t('settings.theme') }}
          </label>
          <ThemeSwitcher />

          <button class="bg-primary hover:bg-primary-dark text-white pl-2 pr-2 rounded">
            {{ t('settings.theme') }}
          </button>
        </div>
      </TabsContent>

      <!-- 大模型配置 -->
      <TabsContent value="models" class="space-y-4">
        <AccordionRoot type="single" collapsible>
          <AccordionItem v-for="provider in providers" :key="provider.id" :value="provider.name" class="border rounded-lg mb-2">
            <AccordionTrigger class="flex items-center justify-between w-full p-4 text-left">
              <div class="flex items-center gap-2">
                <img :src="provider.avatar" :alt="provider.name" class="w-6 h-6 rounded">
                <span class="font-medium">{{ provider.title }}</span>
              </div>
              <Icon icon="radix-icons:chevron-down" class="transform transition-transform duration-200 ease-in-out data-[state=open]:rotate-180" />
            </AccordionTrigger>
            <AccordionContent class="p-4 pt-0">
              <div class="space-y-4">
                <div v-for="config in getProviderConfig(provider.name)" :key="config.key" class="flex items-center gap-4">
                  <label class="text-sm font-medium text-gray-700 w-24">{{ config.label }}</label>
                  <input 
                    :type="config.type"
                    :placeholder="config.placeholder"
                    :required="config.required"
                    :value="config.value"
                    @input="(e) => updateProviderConfig(provider.name, config.key, (e.target as HTMLInputElement).value)"
                    class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-green-500"
                  />
                </div>

                <!-- 连通性测试 -->
                <div class="flex items-center gap-4">
                  <label class="text-sm font-medium text-gray-700 w-24 min-w-24">{{
                    t('settings.testConnection')
                  }}</label>
                  <div class="flex items-center gap-2">
                    <Button
                      class="shrink-0"
                      :color="testingStates[provider.name]?.success === false ? 'red' : 'green'"
                      @click="() => testConnection(provider.name)"
                      :disabled="testingStates[provider.name]?.loading"
                      plain
                      size="small"
                      :loading="testingStates[provider.name]?.loading"
                      :icon-name="getStatusIcon(testingStates[provider.name])"
                    >
                      {{
                        testingStates[provider.name]?.loading
                          ? t('settings.testing')
                          : t('settings.test')
                      }}
                    </Button>
                    <span
                      v-if="testingStates[provider.name]?.message"
                      class="text-sm break-all"
                      :class="
                        testingStates[provider.name]?.success ? 'text-green-700' : 'text-red-500'
                      "
                    >
                      {{ testingStates[provider.name]?.message }}
                    </span>
                  </div>
                </div>

                <!-- 模型列表 -->
                <AccordionRoot type="single" collapsible v-if="hasModels(testingStates[provider.name])">
                  <AccordionItem value="item-1" class="">
                    <AccordionTrigger class="flex items-center justify-between w-full pt-4 text-left">
                      <div class="flex items-center gap-2">
                        <label class="text-sm font-medium text-gray-700 w-24">{{ t('settings.modelList') }}</label>
                      </div>
                      <Icon icon="radix-icons:chevron-down" class="transform transition-transform duration-200 ease-in-out data-[state=open]:rotate-180" />
                    </AccordionTrigger>
                    <AccordionContent>
                      <div class="items-center gap-2 max-h-60 overflow-y-auto">
                        <div 
                          v-for="(model, index) in testingStates[provider.name].models"
                          :key="`${model.id}-${index}`"
                          class="p-4 border-b last:border-b-0 hover:bg-gray-50 transition-colors flex items-center justify-between"
                        >
                          <span class="text-gray-800">{{ model.id }}</span>
                          <label class="relative inline-flex items-center cursor-pointer">
                            <input 
                              type="checkbox"
                              class="sr-only peer"
                            >
                            <div class="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-700"></div>
                          </label>
                        </div>
                      </div>
                    </AccordionContent>
                  </AccordionItem>
                </AccordionRoot>
              </div>
            </AccordionContent>
          </AccordionItem>
        </AccordionRoot>
      </TabsContent>
    </TabsRoot>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, watch, ref, computed } from 'vue'
import { Icon } from '@iconify/vue'
import { useI18n } from 'vue-i18n'
import { AppConfig, ProviderName, ModelItem } from '../types'
import { setI18nLanguage } from '../i18n'
import { useProviderStore } from '../stores/provider'
import ThemeSwitcher from '../components/ThemeSwitcher.vue'
import { providerConfigs, ProviderConfigItem } from '../config/providerConfig'
import Button from '../components/Button.vue'
import {
  SelectContent,
  SelectGroup,
  SelectIcon,
  SelectItem,
  SelectItemIndicator,
  SelectItemText,
  SelectPortal,
  SelectRoot,
  SelectTrigger,
  SelectValue,
  SelectViewport,
  NumberFieldRoot,
  NumberFieldInput,
  NumberFieldIncrement,
  NumberFieldDecrement,
  TabsRoot,
  TabsList,
  TabsTrigger,
  TabsContent,
  AccordionRoot,
  AccordionItem,
  AccordionTrigger,
  AccordionContent,
} from 'radix-vue'

const { t } = useI18n()
const activeTab = ref('general')
const providerStore = useProviderStore()
const providers = computed(() => providerStore.items)

const currentConfig = reactive<AppConfig>({
  language: 'zh',
  fontSize: 14,
  providerConfigs: {}
})

onMounted(async () => {
  const config = await window.electronAPI.getConfig()
  console.log('==onMounted', currentConfig, config)
  Object.assign(currentConfig, config)
})

// 监听配置变化并自动保存
watch(currentConfig, async (newConfig) => {
  // 创建一个普通对象来传递配置
  const configToSave = {
    language: newConfig.language,
    fontSize: newConfig.fontSize,
    providerConfigs: JSON.parse(JSON.stringify(newConfig.providerConfigs))
  }
  console.log('==configToSave', configToSave)
  await window.electronAPI.updateConfig(configToSave)
  // 更新界面语言
  setI18nLanguage(newConfig.language)
}, { deep: true })

// 获取provider对应的配置项
const getProviderConfig = (providerName: string): ProviderConfigItem[] => {
  const configs = providerConfigs[providerName] || []
  // 确保配置值被初始化
  if (!currentConfig.providerConfigs[providerName]) {
    currentConfig.providerConfigs[providerName] = {}
  }
  return configs.map(config => ({
    ...config,
    value: currentConfig.providerConfigs[providerName][config.key] || config.value
  }))
}

// 更新provider配置值
const updateProviderConfig = (providerName: ProviderName, key: string, value: string) => {
  if (!currentConfig.providerConfigs[providerName]) {
    currentConfig.providerConfigs[providerName] = {}
  }
  currentConfig.providerConfigs[providerName][key] = value
}

// 添加测试状态管理
type TestingState = {
  loading: boolean
  success?: boolean
  message?: string
  models?: ModelItem[]
}

const testingStates = ref<Record<ProviderName, TestingState>>(
  {} as Record<ProviderName, TestingState>
)

// 测试连通性方法
const testConnection = async (providerName: ProviderName) => {
  // 设置加载状态
  testingStates.value[providerName] = { loading: true }

  try {
    // 调用主进程的测试接口
    const result = await window.electronAPI.testProviderConnect(providerName)
    console.log('==testConnection-result', result)
    testingStates.value[providerName] = {
      loading: false,
      success: result.success,
      message: result.message,
      models: result?.models ?? []
    }
  } catch (error: any) {
    testingStates.value[providerName] = {
      loading: false,
      success: false,
      message: `${t('settings.testFailed')}${error.message || '未知错误'}`,
    }
  }
}

const getStatusIcon = (state: TestingState) => {
  if (!state?.success && !state?.message) return 'lucide:wifi'
  return state?.success ? 'lucide:check-circle' : 'lucide:x-circle'
}

const hasModels = (state: TestingState) => {
  if (state?.models && state.models.length > 0) {
    return true;
  }
  return false;
}
</script>

<style scoped>
.w-\[80\%\] {
  max-height: calc(100vh - 2rem);
  overflow-y: auto;
}
.max-h-60::-webkit-scrollbar {
  width: 6px;
}

.max-h-60::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.max-h-60::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.max-h-60::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>